class Solution {
    vector<int> ret;
    vector<int> index;
    int tmpN[500010];
    int tmpI[500010];
public:
    vector<int> countSmaller(vector<int>& nums) {
        ret.resize(nums.size());
        index.resize(nums.size());
        for(int i=0;i<nums.size();i++)index[i]=i;
        mergeSort(nums,0,nums.size()-1);
        return ret;
    }
    void mergeSort(vector<int>& nums,int left,int right)
    {
        if(left>=right)return;
        int mid=(left+right)>>1;
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);
        int cur1=left,cur2=mid+1,i=0;
        while(cur1<=mid&&cur2<=right)
        {
            if(nums[cur1]<=nums[cur2])
            {
                tmpN[i]=nums[cur2];
                tmpI[i]=index[cur2];
                i++;cur2++;
            }
            else
            {
                ret[index[cur1]]+=right-cur2+1;
                tmpN[i]=nums[cur1];
                tmpI[i]=index[cur1];
                i++;cur1++;
            }
        }

        while(cur1<=mid)
        {
                tmpN[i]=nums[cur1];
                tmpI[i]=index[cur1];
                i++;cur1++;
        }
        while(cur2<=right)
        {
                tmpN[i]=nums[cur2];
                tmpI[i]=index[cur2];
                i++;cur2++;
        }
        for(int j=left;j<=right;j++)
        {
            nums[j]=tmpN[j-left];
            index[j]=tmpI[j-left];
        }
    }
};
